<template>
    <LayoutWrap class="bill-list">
        <el-form @submit.native.prevent ref="formSearch" :inline="true" :model="formSearch" label-width="80px">
            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="时间区间" prop="startDate">
                        <el-date-picker
                            type="date"
                            placeholder="选择日期"
                            format="yyyy/MM/dd"
                            prefix-icon="false"
                            v-model="formSearch.startDate"
                            :clearable="true"
                            class="custom-the-datepicker"
                            style="width: 88px;margin-right: 5px;"
                            @change="onChangeDate($event, 'startDate')"
                            @keyup.enter.native="getList"
                        ></el-date-picker>
                        <el-time-select
                            prefix-icon="false"
                            placeholder="起始时间"
                            v-model="formSearch.startTime"
                            class="custom-the-datepicker"
                            style="width: 60px;"
                            :clearable="false"
                            :picker-options="{
                                start: '00:00',
                                step: '01:00',
                                end: '24:00'
                            }"
                            @change="onChangeDate($event, 'startTime')"
                            @keyup.enter.native="getList"
                        >
                        </el-time-select>
                        <span style="display: inline-block; padding: 0 5px;">-</span>
                        <el-date-picker
                            type="date"
                            placeholder="选择日期"
                            format="yyyy/MM/dd"
                            prefix-icon="false"
                            v-model="formSearch.endDate"
                            :clearable="true"
                            class="custom-the-datepicker"
                            style="width: 88px;margin-right: 5px;"
                            @change="onChangeDate($event, 'endDate')"
                            @keyup.enter.native="getList"
                        ></el-date-picker>
                        <el-time-select
                            prefix-icon="false"
                            placeholder="结束时间"
                            v-model="formSearch.endTime"
                            class="custom-the-datepicker"
                            style="width: 60px; margin-right: 5px;"
                            :clearable="false"
                            :picker-options="{
                                start: '00:00',
                                step: '01:00',
                                end: '24:00'
                            }"
                            @change="onChangeDate($event, 'endTime')"
                            @keyup.enter.native="getList"
                        >
                        </el-time-select>
                    </el-form-item>
                </div>
                <div class="search-item right" prop="status">
                    <el-form-item label="交易状态">
                        <el-select v-model="formSearch.status" placeholder="请选择" style="width: 120px;">
                            <el-option
                                v-for="item in statusOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
            </div>
            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="关键词" prop="keyName">
                        <el-select
                            class="custom-the-select_key"
                            popper-class="custom-the-select-popper_key"
                            v-model="formSearch.keyName"
                            placeholder="请选择"
                            style="width: 105px;margin-right: 10px;"
                        >
                            <el-option
                                v-for="item in keyOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                :disabled="item.disabled"
                            >
                            </el-option>
                        </el-select>
                        <br v-if="isMobile" />
                        <el-input
                            v-model="formSearch.keyValue"
                            @keyup.enter.native="getBillLatest"
                            style="width: 205px"
                        ></el-input>
                    </el-form-item>
                </div>

                <div class="search-item right">
                    <el-form-item label="时间类型">
                        <el-select v-model="formSearch.dateType" placeholder="请选择" style="width: 120px;">
                            <el-option
                                v-for="item in dateTypeOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                :disabled="item.disabled"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
            </div>
            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="金额范围">
                        <el-input
                            v-model="formSearch.amountRangeStart"
                            @keyup.enter.native="getBillLatest"
                            style="width: 143px;"
                        ></el-input>
                        <span style="display: inline-block; margin: 0 15px">-</span>
                        <br v-if="isMobile" />
                        <el-input
                            v-model="formSearch.amountRangeEnd"
                            @keyup.enter.native="getBillLatest"
                            style="width: 143px;"
                        ></el-input>
                    </el-form-item>
                </div>
                <div class="search-item right">
                    <el-form-item label="资金流向">
                        <el-select v-model="formSearch.capitalFlows" placeholder="请选择" style="width: 120px;">
                            <el-option
                                v-for="item in capitalFlowsOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                :disabled="item.disabled"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
            </div>
            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="  ">
                        <el-button type="primary" style="min-width: 120px;" @click="getBillLatest">查询</el-button>
                        <br v-if="isMobile" />
                        <el-button type="default" style="min-width: 120px;" @click="resetForm('formSearch')"
                            >重置</el-button
                        >
                    </el-form-item>
                </div>
            </div>
        </el-form>
        <h3 class="table-header">统计</h3>
        <el-table :data="statistics" border style="width: 100%" v-loading="isLoading">
            <el-table-column v-if="!isMobile" type="index"> </el-table-column>
            <el-table-column prop="_id" key="_id" label="状态" align="center">
                <template v-slot="{row}">
                    <div style="display: inline-flex; flex-flow: row nowrap; align-items: center;">
                        <span :title="row._id | getBillStatusText" :class="row._id | getBillStatusColor"> </span>
                        <span style="margin-left: 10px;">{{ row._id | getBillStatusText }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="value" key="value" label="总金额（￥）" align="center"> </el-table-column>
            <el-table-column prop="count" key="count" label="账单数量" align="center"> </el-table-column>
        </el-table>

        <h3 class="table-header">详细数据</h3>
        <ul class="edit-bar" style="margin-bottom: 10px">
            <li>
                <el-popover placement="top" width="160" v-model="visibleUpdate">
                    <p>确认批量修改下面选中数据吗？</p>
                    <div style="text-align: right; margin: 0">
                        <el-button
                            size="mini"
                            type="text"
                            :disabled="isLoading || !isMultSelect"
                            @click="visible = false"
                            >取消</el-button
                        >
                        <el-button type="primary" size="mini" :disabled="isLoading || !isMultSelect" @click="handleOk"
                            >确定</el-button
                        >
                    </div>
                    <el-button slot="reference" :disabled="isLoading || !isMultSelect">确认修改</el-button>
                </el-popover>
            </li>
            <li>
                <el-button :disabled="isLoading || !isMultSelect" @click="handleCancel" type="default"
                    >取消选中</el-button
                >
            </li>
            <li>
                <el-select
                    :disabled="isLoading || !isMultSelect"
                    v-model="multSelectStatus"
                    placeholder="选择还款状态"
                    style="width: 150px;"
                >
                    <el-option label="还款中" :value="1"></el-option>
                    <el-option label="已结清" :value="2"></el-option>
                    <el-option label="已逾期" :value="3"></el-option>
                </el-select>
            </li>
        </ul>
        <el-table
            ref="singleTable"
            style="width: 100%"
            border
            show-summary
            v-loading="isLoading"
            :summary-method="getSummaries"
            :data="rankings"
            @selection-change="handleSelectionChange"
            class="table-line-clamp"
        >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column type="index" :index="indexMethod"> </el-table-column>
            <el-table-column prop="stages.status" key="stages.status" label="状态" :width="60" align="center" sortable>
                <template v-slot="{row}">
                    <span
                        :title="row.stages.status | getBillStatusText"
                        :class="row.stages.status | getBillStatusColor"
                    >
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="stages.date" key="stages.date" label="还款日期" sortable> </el-table-column>
            <el-table-column prop="fromMoney" key="fromMoney" label="还款金额（￥）" sortable> </el-table-column>
            <el-table-column prop="fromName" key="fromName" label="账单名称" sortable>
                <template v-slot="{row}">
                    <el-button :disabled="!row._id" @click="handleDetail(row)" type="text" style="user-select: unset;">
                        {{ row.fromName }}
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column prop="stages.stage" key="stages.stage" label="当前期数/总期数" sortable>
                <template v-slot="{row}">
                    {{ `${row.stages.stage}/${row.stage_total}` }}
                </template>
            </el-table-column>
            <el-table-column prop="platform" key="platform" label="借款平台" sortable>
                <template v-slot="{row}">
                    <el-button
                        :disabled="!row._id"
                        @click="$router.push({name: PLATFORM, query: {name: row.platform ? row.platform.name : ''}})"
                        type="text"
                        style="user-select: unset;"
                    >
                        {{ row.platform ? row.platform.name : '' }}
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column prop="from_time" key="from_time" label="借款日期" sortable> </el-table-column>
            <el-table-column prop="create_date" key="create_date" label="创建时间" sortable> </el-table-column>
            <el-table-column prop="remark" key="remark" label="备注">
                <!-- <template v-slot="{row}">
                    {{ row.remark && row.remark.length >= 30 ? `${row.remark.slice(0, 30)}...` : row.remark }}
                </template> -->
            </el-table-column>
        </el-table>
        <Pagination
            :page-size.sync="formSearch.pageSize"
            :page.sync="formSearch.page"
            :total="formSearch.count"
            :pageSizes="[5, 10, 20, 30, 50, 100, 200]"
            @change="getBillLatest"
        />
    </LayoutWrap>
</template>

<script>
import {getBillLatest, putBillLatest} from '@/api/home';
import moment from 'moment';
import {keep2decimalPlaces, getBillStatusText, getBillStatusColor} from '@/filters';
import {BASIC_MONEY, THE_MOMENT_YYMMDD, THE_MOMENT_YYMMDD_HHMMSS} from '@/utils/constant';
import {BILL_LIST_DETAIL, PLATFORM} from '@/router/route-name';
import {mapGetters} from 'vuex';
import {BILL_STATUS_REPAYMENT, BILL_STATUS_SETTLED, BILL_STATUS_PAST_DUE} from '@/views/bill/constant-bill';
export default {
    filters: {
        getBillStatusColor,
        getBillStatusText
    },
    data() {
        const dateNumber = new Date().getDate();
        let startDate;
        let endDate;
        if (dateNumber >= 15) {
            startDate = moment().format('YYYY-MM-15');
            endDate = moment()
                .add(1, 'months')
                .format('YYYY-MM-15');
        } else {
            startDate = moment()
                .add(-1, 'months')
                .format('YYYY-MM-15');
            endDate = moment().format('YYYY-MM-15');
        }

        return {
            PLATFORM,
            menuOptions: [
                {label: '所有时间', value: 'All'},
                {label: '自定义时间', value: 'CustomTime'},
                {label: '今天', value: 'Today'},
                {label: '最近一周', value: 'LastWeek'},
                {label: '最近一个月', value: 'LastMonth'},
                {label: '最近三个月', value: 'LastThreeMonths'}
            ],
            keyOptions: [
                {label: '流水号', value: 'SerialNumber', disabled: true},
                {label: '备注信息', value: 'TradingInformation', disabled: false},
                {label: '账单名称', value: 'CounterpartyName', disabled: false}
            ],
            dateTypeOptions: [
                {label: '创建时间', value: 'create_date', disabled: false},
                {label: '还款时间', value: 'stages.date', disabled: false},
                {label: '借款时间', value: 'from_time', disabled: false}
            ],
            statusOptions: [
                {label: '所有状态', value: '1,2,3'},
                {label: '还款中(含逾期)', value: '1,3'},
                {label: '还款中', value: '1'},
                {label: '已结清', value: '2'},
                {label: '已逾期', value: '3'}
            ],
            capitalFlowsOptions: [
                {label: '全部', value: '1', disabled: true},
                {label: '收入', value: '2', disabled: true},
                {label: '支出', value: '3', disabled: true}
            ],
            formSearch: {
                selectMenu: 'CustomTime', // 'CustomTime' 'LastWeek',
                startDate: startDate,
                startTime: '00:00',
                endDate: endDate,
                endTime: '24:00',
                keyName: 'CounterpartyName',
                keyValue: '',
                amountRangeStart: '',
                amountRangeEnd: '',
                dateType: 'stages.date',
                status: '1,3', // 交易状态
                capitalFlows: '1',
                page: 1,
                pageSize: 10,
                count: 0 // 总条数
            },
            rankings: [], // 表格数据
            statistics: [], // 统计数据
            dataNow: null,
            multipleSelection: [], // 多选
            isLoading: false,
            multSelectStatus: BILL_STATUS_SETTLED, // 还款状态
            BILL_STATUS_REPAYMENT,
            BILL_STATUS_SETTLED,
            BILL_STATUS_PAST_DUE,
            visibleUpdate: false
        };
    },
    computed: {
        ...mapGetters({
            isMobile: 'app/isMobile'
        }),
        isMultSelect() {
            return this.multipleSelection.length > 0;
        }
    },
    created() {
        const newItem = {...this.formSearch, ...this.$route.query};
        if (newItem.page) newItem.page = newItem.page - 0;
        if (newItem.pageSize) newItem.pageSize = newItem.pageSize - 0;
        if (newItem.count) newItem.count = newItem.count - 0;

        // if (newItem.selectMenu) {
        //     this.selectMenu = newItem.selectMenu;

        //     delete newItem.selectMenu;
        // }

        this.formSearch = newItem;
        this.getBillLatest();
    },
    methods: {
        onChangeDate(value, type) {
            this.formSearch.selectMenu = 'CustomTime';

            if (type === 'startDate' && !value) {
                this.formSearch = {...this.formSearch, startTime: ''};
            }
            if (type === 'startDate' && value && !this.formSearch.startTime) {
                this.formSearch = {...this.formSearch, startTime: '00:00'};
            }

            if (type === 'startDate' && value) {
                this.formSearch = {
                    ...this.formSearch,
                    endDate: moment(new Date(value))
                        .add(1, 'months')
                        .format('YYYY-MM-DD')
                };
            }

            if (type === 'endDate' && !value) {
                this.formSearch = {...this.formSearch, endTime: ''};
            }
            if (type === 'endDate' && value && !this.formSearch.endTime) {
                this.formSearch = {...this.formSearch, endTime: '24:00'};
            }
        },
        // 确认修改
        async handleOk() {
            this.visibleUpdate = false;
            console.log('确认修改');
            this.isLoading = true;
            try {
                const multSelectStatus = this.multSelectStatus;
                const newItems = this.multipleSelection.map(item => {
                    return {_id: item._id, stages: {_id: item.stages._id, status: multSelectStatus}};
                });
                await putBillLatest(newItems);
                this.$message({showClose: true, type: 'success', message: '批量修改成功'});
            } catch (error) {
                this.$message({showClose: true, type: 'error', message: '批量修改失败'});
                console.error(error);
            } finally {
                this.isLoading = false;
            }
            this.getBillLatest();
        },
        // 取消修改
        handleCancel() {
            this.$refs.singleTable.clearSelection();
        },
        handleSelectionChange(value) {
            this.visibleUpdate = false;
            this.multipleSelection = value;
            this.multSelectStatus = BILL_STATUS_SETTLED;
        },
        getBillLatest() {
            this.isLoading = true;
            this.dataNow = new Date().getTime();
            const formSearch = this.formSearch;
            const selectMenu = formSearch.selectMenu;
            let startDate;
            let endDate;

            switch (selectMenu) {
                case 'All': {
                    startDate = undefined;
                    endDate = undefined;
                    break;
                }
                case 'Today': {
                    startDate = new Date(moment().format('YYYY-MM-DD 00:00:00'));
                    endDate = new Date(moment().format('YYYY-MM-DD 23:59:59'));
                    break;
                }
                case 'LastWeek': {
                    startDate = moment().add(-7, 'days');
                    endDate = moment().add(7, 'days');
                    break;
                }
                case 'LastMonth': {
                    startDate = moment().add(-1, 'months');
                    endDate = moment().add(1, 'months');
                    break;
                }
                case 'LastThreeMonths': {
                    startDate = moment().add(-3, 'months');
                    endDate = moment().add(3, 'months');
                    break;
                }
                case 'CustomTime': {
                    if (formSearch.startDate && formSearch.startTime) {
                        startDate = `${moment(formSearch.startDate).format('YYYY-MM-DD')} ${formSearch.startTime}`;
                    }
                    if (formSearch.endDate && formSearch.endTime) {
                        endDate = `${moment(formSearch.endDate).format('YYYY-MM-DD')} ${formSearch.endTime}`;
                    }
                    break;
                }
            }

            const newItem = {
                page: formSearch.page,
                pageSize: formSearch.pageSize,
                status: formSearch.status,
                startDate: startDate ? new Date(startDate) : undefined,
                endDate: endDate ? new Date(endDate) : undefined,
                dateType: formSearch.dateType
            };
            console.error(newItem);

            if (formSearch.keyName === 'CounterpartyName' && formSearch.keyValue) {
                newItem.name = formSearch.keyValue;
            }
            if (formSearch.keyName === 'TradingInformation' && formSearch.keyValue) {
                newItem.remark = formSearch.keyValue;
            }
            if (formSearch.amountRangeStart) {
                newItem.amountRangeStart = (formSearch.amountRangeStart * BASIC_MONEY).toFixed(2);
            }
            if (formSearch.amountRangeEnd) {
                newItem.amountRangeEnd = (formSearch.amountRangeEnd * BASIC_MONEY).toFixed(2);
            }

            this.$router.push({query: {...formSearch, selectMenu}});

            getBillLatest(newItem)
                .then(({data: res}) => {
                    if (res.status === 200) {
                        const {data, page, pageSize, statistics} = res;
                        this.rankings = data.map(i => {
                            return {
                                ...i,
                                fromName: i.name,
                                fromMoney: keep2decimalPlaces(i.stages.cash / BASIC_MONEY),
                                create_date: moment(i.create_date).format(THE_MOMENT_YYMMDD_HHMMSS),
                                from_time: moment(i.from_time).format(THE_MOMENT_YYMMDD),
                                stages: {
                                    ...i.stages,
                                    date: moment(i.stages.date).format(THE_MOMENT_YYMMDD)
                                }
                            };
                        });
                        const count = statistics.reduce((total, i) => total + i.count, 0);
                        this.formSearch = {...this.formSearch, page, pageSize, count};

                        this.statistics = statistics.map(item => {
                            return {...item, value: keep2decimalPlaces(item.value / BASIC_MONEY)};
                        });
                    } else {
                        throw res;
                    }
                })
                .catch(error => {
                    console.error(error);
                    this.$message({type: 'error', message: '获取账单失败'});
                })
                .finally(() => (this.isLoading = false));
        },
        handleDetail(row) {
            this.$router.push({name: BILL_LIST_DETAIL, query: {type: 'detail', id: row._id}});
        },
        indexMethod(index) {
            return index + 1 + (this.formSearch.page - 1) * this.formSearch.pageSize;
        },
        getSummaries(param) {
            const {columns, data} = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.some(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return prev + curr * BASIC_MONEY;
                        } else {
                            return prev;
                        }
                    }, 0);
                    sums[index] = sums[index] / BASIC_MONEY;
                } else {
                    sums[index] = 'N/A';
                }
            });

            return sums;
        },
        resetForm() {
            const dateNumber = new Date().getDate();
            let startDate;
            let endDate;
            if (dateNumber >= 15) {
                startDate = moment().format('YYYY-MM-15');
                endDate = moment()
                    .add(1, 'months')
                    .format('YYYY-MM-15');
            } else {
                startDate = moment()
                    .add(-1, 'months')
                    .format('YYYY-MM-15');
                endDate = moment().format('YYYY-MM-15');
            }

            this.formSearch = {
                ...this.$options.data().formSearch
            };
        }
    }
};
</script>
<style lang="scss" scoped>
.edit-bar {
    display: flex;
    flex-flow: row wrap;
    & > li + li {
        margin-left: 16px;
    }
}
</style>
<style lang="scss">
.custom-the-select-popper_time {
    position: absolute;
    left: -1px !important;
    width: 100px !important;
    .el-select-dropdown__item {
        padding-left: 10px;
        padding-right: 10px;
    }
}
.custom-the-select-popper_key {
    .el-select-dropdown__item {
        padding-left: 10px;
        padding-right: 10px;
    }
}
.custom-the-select-popper_time.CustomTime {
    position: absolute;
    left: -325px !important;
    width: 361px !important;
}
</style>
<style lang="scss" scoped>
.table-header {
    margin: 30px 0 20px 0;
}
.custom-the-datepicker,
.custom-the-select_time,
.custom-the-select_key {
    ::v-deep {
        .el-input__inner {
            padding-left: 10px;
            padding-right: 10px;
        }
    }
}
.custom-the-select_time {
    width: 105px;
}
.custom-the-select_time.CustomTime {
    ::v-deep {
        .el-input__inner {
            color: #fff;
        }
    }
}
.custom-the-select_time.CustomTime {
    width: 35px;
}

.search-wrap {
    display: flex;
    flex-flow: row wrap;
    .search-item.left {
        min-width: 455px;
    }
}
</style>
